package com.example.woke;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.woke.method.MyApp;
import com.woke.photoactivity.Bimp;
import com.zhongcai.online.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class CreditziliaoActivity extends Activity {

	private LinearLayout mLinearLayout;
	private MyApp myapp;
	private int phonewihd;
	private ImageView mView1,mView2,mView3;
	private static final int PHOTO_CAPTURE = 0x11;
	private String photoPath = "/sdcard/zhongcai/";
	private String photoName = photoPath + "zhongcai.jpg";
	private String newName = "";
	Uri imageUri = Uri.fromFile(new File(Environment
			.getExternalStorageDirectory(), "image.jpg"));
	private ArrayList<String> listurl = new ArrayList<String>();
	private String mapurl1 = "";
	private String mapurl2 = "";
	private String mapurl3 = "";
	private int whichmap=0;
	private Intent intent;
	private TextView mTfor;
	private String trim;
	private ArrayList<String> maplist;
	private TextView mTView1,mTView2,mTView3;
	private RelativeLayout mLayout1;
	private RelativeLayout mLayout2;
	private RelativeLayout mLayout3;
	private ImageView mIma1,mIma2,mIma3;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_creditziliao);
		
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		.detectDiskReads()
		.detectDiskWrites()
		.detectNetwork() 
		.penaltyLog()
		.build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
		.detectLeakedSqlLiteObjects()
		.penaltyLog()
		.penaltyDeath()
		.build());
		
//		intent = new Intent();
//		
		intent = getIntent();
		trim = intent.getStringExtra("trim");
		maplist = intent.getStringArrayListExtra("maplist");
		myapp = (MyApp) getApplication();
		phonewihd = myapp.screenWidth;
		intview();
		
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		
		
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode == RESULT_OK && requestCode == 1) {  
			 Bitmap bm = null;
			 BitmapFactory.Options op = new BitmapFactory.Options();
				op.inSampleSize = 4; 
				ContentResolver resolver = getContentResolver();
					try {
						Uri originalUri = data.getData(); // ���ͼƬ��uri
						String[] proj = { MediaStore.Images.Media.DATA };
						Cursor cursor = managedQuery(originalUri, proj, null, null,
								null);
						// ���Ҹ������ ����ǻ���û�ѡ���ͼƬ������ֵ
						int column_index = cursor
								.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
						cursor.moveToFirst();
						// ���������ֵ��ȡͼƬ·��
						String path = cursor.getString(column_index);
						
						bm = BitmapFactory.decodeFile(path,op);
						
//						bm = MediaStore.Images.Media.getBitmap(resolver, originalUri); // �Եõ�bitmapͼƬ
						if(whichmap == 1){
							mapurl1 = path;
							mView1.setVisibility(View.VISIBLE);
							mView1.setImageBitmap(bm);
						}else if(whichmap == 2){
							mapurl2 = path;
							mView2.setVisibility(View.VISIBLE);
							mView2.setImageBitmap(bm);
						}else{
							mapurl3 = path;
							mView3.setVisibility(View.VISIBLE);
							mView3.setImageBitmap(bm);
						}
						// ���￪ʼ�ĵڶ����֣���ȡͼƬ��·����
//						Log.e("Lostinai", path);

					} catch (OutOfMemoryError e) {
					    //
						Toast.makeText(CreditziliaoActivity.this, "图片获取失败，请重试", Toast.LENGTH_SHORT).show();
					}
	        } 
		
		
		String sdStatus = Environment.getExternalStorageState();
		switch (requestCode) {
		case PHOTO_CAPTURE:
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
			} else {
				BitmapFactory.Options op = new BitmapFactory.Options();
				op.inSampleSize = 4; 
				Bitmap bitMap = BitmapFactory.decodeFile(photoName,op);
				int width = bitMap.getWidth();
				int height = bitMap.getHeight();
				int newWidth = 480;
				int newHeight = 640;
				float scaleWidth = ((float) newWidth) / width;
				float scaleHeight = ((float) newHeight) / height;
				Matrix matrix = new Matrix();
				matrix.postScale(scaleWidth, scaleHeight);
				bitMap = Bitmap.createBitmap(bitMap, 0, 0, width, height,
						matrix, true);
				Bitmap pic = null;
				pic = BitmapFactory.decodeFile(photoName, op);
				if(whichmap == 1){
					mView1.setVisibility(View.VISIBLE);
					mView1.setImageBitmap(pic);
					mapurl1 = photoName; 
				}else if(whichmap == 2){
					mView2.setImageBitmap(pic);
					mView2.setVisibility(View.VISIBLE);
					mapurl2 = photoName; 
				}else if(whichmap == 3){
					mView3.setImageBitmap(pic);
					mView3.setVisibility(View.VISIBLE);
					mapurl3 = photoName; 
				}
				FileOutputStream b = null;
				;
				try {
					b = new FileOutputStream(photoName);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
				if (pic != null) {
					pic.compress(Bitmap.CompressFormat.JPEG, 50, b);
				}
			}
			break;
			
		default:
			return;
		}
	}
	
	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, final int i) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(view, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					photo();
					dismiss();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
//					Intent intent = new Intent();  
//	                /* ����Pictures����Type�趨Ϊimage */  
//	                intent.setType("image/*");  
//	                /* ʹ��Intent.ACTION_GET_CONTENT���Action */  
//	                intent.setAction(Intent.ACTION_GET_CONTENT);   
//	                /* ȡ����Ƭ�󷵻ر����� */  
//	                startActivityForResult(intent, 1);
	                
	                Intent i = new Intent(
	   				Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
	   				startActivityForResult(i, 1);
	                
					dismiss();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});
		}
	}
	
	private void photo() {
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		File file = new File(photoPath);
		if (!file.exists()) { 
			file.mkdir(); 
		}
		String stringDate = getUserDate("yyyyMMddhhmmss");
		newName = stringDate+".jpg";
		Log.e("stringDate", stringDate);
		photoName = photoPath + stringDate+".jpg";
		File photo = new File(photoName);
		imageUri = Uri.fromFile(photo);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); 
		startActivityForResult(intent, PHOTO_CAPTURE);
	}
	
	public static String getUserDate(String sformat) {
		  Date currentTime = new Date();
		  SimpleDateFormat formatter = new SimpleDateFormat(sformat);
		  String dateString = formatter.format(currentTime);
		  return dateString;
		}

	private void intview() {
		
		Myhotpreciver reciver = new Myhotpreciver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.woke.whyalwaysfalse");
		CreditziliaoActivity.this.registerReceiver(reciver, filter);
		
		mTView1 = (TextView) findViewById(R.id.avcredit_ziliao_text1);
		mTView2 = (TextView) findViewById(R.id.avcredit_ziliao_text2);
		mTView3 = (TextView) findViewById(R.id.avcredit_ziliao_text3);
		
		mIma1 = (ImageView) findViewById(R.id.avcredit_zilia_bg1);
		mIma2 = (ImageView) findViewById(R.id.avcredit_zilia_bg2);
		mIma3 = (ImageView) findViewById(R.id.avcredit_zilia_bg3);
		
		findViewById(R.id.avcredit_ziliao_backtext).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				if(!mapurl1.equals("")){
					listurl.add(mapurl1);
				}if(!mapurl2.equals("")){
					listurl.add(mapurl2);
				}if(!mapurl3.equals("")){
					listurl.add(mapurl3);
				}
//				Intent intent = new Intent();
				intent.putExtra("listurl", listurl);
				setResult(302, intent);
				finish();
			}
		});
		
		mTfor = (TextView) findViewById(R.id.avcredit_ziliao_textfor);
		mTfor.setText(trim);
		mLinearLayout = (LinearLayout) findViewById(R.id.avcredit_ziliao_linear);
		
		mView1 = (ImageView) findViewById(R.id.avcredit_ziliao_1);
		mView2 = (ImageView) findViewById(R.id.avcredit_ziliao_2);
		mView3 = (ImageView) findViewById(R.id.avcredit_ziliao_3);
		
		mLayout1 = (RelativeLayout) findViewById(R.id.avcredit_ziliao_r1);
		mLayout2 = (RelativeLayout) findViewById(R.id.avcredit_ziliao_r2);
		mLayout3 = (RelativeLayout) findViewById(R.id.avcredit_ziliao_r3);
		LayoutParams params1 = mLayout1.getLayoutParams();
		params1.width = phonewihd / 3 - 15;
		params1.height = phonewihd / 3 - 15;
		mLayout1.setLayoutParams(params1);
		
		LayoutParams params2 = mLayout2.getLayoutParams();
		params2.width = phonewihd / 3 - 15;
		params2.height = phonewihd / 3 -15;
		mLayout2.setLayoutParams(params1);
		
		LayoutParams params3 = mLayout3.getLayoutParams();
		params3.width = phonewihd/ 3 - 15;
		params3.height = phonewihd / 3 - 15;
		mLayout3.setLayoutParams(params3);
		
		mLayout1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				whichmap = 1;
				new PopupWindows(CreditziliaoActivity.this,1);
			}
		});
		
		mLayout2.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				whichmap = 2;
				new PopupWindows(CreditziliaoActivity.this,2);
			}
		});
		
		mLayout3.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				whichmap = 3;
				new PopupWindows(CreditziliaoActivity.this,3);
			}
		});
		
		findViewById(R.id.avcredit_ziliao_back).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				finish();
			}
		});
		
		if(maplist.size() == 1){
			mLayout3.setBackgroundColor(getResources().getColor(R.color.white));
			mLayout3.setClickable(false);
			mLayout2.setBackgroundColor(getResources().getColor(R.color.white));
			mLayout2.setClickable(false);
			mTView1.setText(maplist.get(0));
			mTView2.setText("");
			mTView3.setText("");
			mIma2.setVisibility(View.GONE);
			mIma3.setVisibility(View.GONE);
			}else if(maplist.size() == 2){
				mLayout3.setBackgroundColor(getResources().getColor(R.color.white));
				mLayout3.setClickable(false);
				mTView1.setText(maplist.get(0));
				mTView2.setText(maplist.get(1));
				mTView3.setText("");
				mIma3.setVisibility(View.GONE);
			}else{
				mTView1.setText(maplist.get(0));
				mTView2.setText(maplist.get(1));
				mTView3.setText(maplist.get(2));
			}
		
	}
	
	class Myhotpreciver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			
			Bundle extras = intent.getExtras();
			String feyanUsersId = extras.getString("feyanUsersIdr");
//			Log.e("��Ƭ", "��ַ"+feyanUsersId);
			if(null != feyanUsersId){
				try {
					Bitmap bitmap = Bimp.revitionImageSize(feyanUsersId);
					if(whichmap == 1){
						mView1.setVisibility(View.VISIBLE);
						mView1.setImageBitmap(bitmap);
						mapurl1 = feyanUsersId; 
					}else if(whichmap == 2){
						mView2.setImageBitmap(bitmap);
						mView2.setVisibility(View.VISIBLE);
						mapurl2 = feyanUsersId; 
					}else if(whichmap == 3){
						mView3.setImageBitmap(bitmap);
						mView3.setVisibility(View.VISIBLE);
						mapurl3 = feyanUsersId; 
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}
